<<<<<<< HEAD
from . import login_bp 
from flask import request,jsonify
from app.models import User,LoginLog,OperationLog,ModuleType,OperationType
=======
from . import login_bp
from flask import request, jsonify
from app.models import User, LoginLog, OperationLog, ModuleType, OperationType
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
from config import Config
from app.extensions import db
from werkzeug.security import generate_password_hash
import datetime
import jwt
from app.decorator import permission_required


@login_bp.route('/login', methods=['POST'])
def login():
    email = request.json.get('email')
    password = request.json.get('password')
<<<<<<< HEAD
    
=======

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    ip = request.remote_addr
    user_agent = request.headers.get('User-Agent')

    user = User.query.filter_by(email=email).first()
<<<<<<< HEAD
    
    if not user:
        login_log = LoginLog(email=email, ip=ip, user_agent=user_agent, 
                           status=False, fail_reason='用户不存在')
        db.session.add(login_log)
        db.session.commit()
        return jsonify({'message':'用户不存在','errcode':'-1'}),401
    
    if not user.check_password(password):
        login_log = LoginLog(email=email, ip=ip, user_agent=user_agent,
                           status=False, fail_reason='密码错误')
        db.session.add(login_log)
        db.session.commit()
        return jsonify({'message':'密码错误','errcode':'-1'}),401
    
    if not user.is_active:
        login_log = LoginLog(email=email, ip=ip, user_agent=user_agent,
                           status=False, fail_reason='用户已禁用')
        db.session.add(login_log)
        db.session.commit()
        return jsonify({'message':'用户已禁用','errcode':'-1'}),401

    login_log = LoginLog(email=email, ip=ip, user_agent=user_agent, status=True)
    db.session.add(login_log)
    db.session.commit()
    
    token = jwt.encode({
        'user_id': user.id,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
    }, Config.SECRET_KEY, algorithm='HS256')

    return jsonify({'message':'登陆成功','errcode':'0', 'token': token}),200
=======

    if not user:
        login_log = LoginLog(email=email, ip=ip, user_agent=user_agent,
                             status=False, fail_reason='用户不存在')
        db.session.add(login_log)
        db.session.commit()
        return jsonify({'message': '用户不存在', 'errcode': '-1'}), 401
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c

    if not user.check_password(password):
        login_log = LoginLog(email=email, ip=ip, user_agent=user_agent,
                             status=False, fail_reason='密码错误')
        db.session.add(login_log)
        db.session.commit()
        return jsonify({'message': '密码错误', 'errcode': '-1'}), 401

    if not user.is_active:
        login_log = LoginLog(email=email, ip=ip, user_agent=user_agent,
                             status=False, fail_reason='用户已禁用')
        db.session.add(login_log)
        db.session.commit()
        return jsonify({'message': '用户已禁用', 'errcode': '-1'}), 401

    login_log = LoginLog(email=email, ip=ip,
                         user_agent=user_agent, status=True)
    db.session.add(login_log)
    db.session.commit()

    token = jwt.encode({
        'user_id': user.id,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
    }, Config.SECRET_KEY, algorithm='HS256')

    return jsonify({'message': '登陆成功', 'errcode': '0', 'token': token}), 200


@login_bp.route('/user/info', methods=['GET'])
def user_info():
    token = request.headers.get('Authorization')
    if not token:
        return jsonify({'message': '未登录', 'errcode': '-1'}), 401
    try:
        if token.startswith('Bearer '):
            token = token.split(' ')[1]
        data = jwt.decode(token, Config.SECRET_KEY, algorithms=['HS256'])
        user_id = data['user_id']
        user = User.query.get(user_id)
        if user.profile and user.profile.name:
            name = user.profile.name
        else:
            name = user.email
        role = user.role.code if user.role.code else ''
<<<<<<< HEAD
        return jsonify({'message':'获取用户信息成功','errcode':'0','name':name,'role':role,'id':user_id}),200
=======
        return jsonify({'message': '获取用户信息成功', 'errcode': '0', 'name': name, 'role': role, 'id': user_id}), 200
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    except jwt.ExpiredSignatureError:
        return jsonify({'message': 'token过期', 'errcode': '-1'}), 401
    except jwt.InvalidTokenError:
<<<<<<< HEAD
        return jsonify({'message':'token无效','errcode':'-1'}),401


@login_bp.route('/reset_password',methods=['POST'])
=======
        return jsonify({'message': 'token无效', 'errcode': '-1'}), 401


@login_bp.route('/reset_password', methods=['POST'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_USER, OperationType.RESET_PASSWORD)
def reset_password():
    id = request.json.get('id')
    uid = request.json.get('uid')
    user = User.query.get(id)
    user.password = generate_password_hash(Config.INIT_PASSWORD)
    try:
        db.session.commit()
        uid_user = User.query.get(uid)
<<<<<<< HEAD
        operation_log = OperationLog(user_id=uid,email=uid_user.email,module=ModuleType.ADMIN_USER,operation=OperationType.RESET_PASSWORD,detail=f'重置 {uid_user.email} 的密码')
        db.session.add(operation_log)
        db.session.commit()
        return jsonify({'message':'重置密码成功','errcode':'0'}),200
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify({'message':'重置密码失败','errcode':'-1','error':str(e)}),500

@login_bp.route('/change_password',methods=['POST'])
=======
        operation_log = OperationLog(user_id=uid, email=uid_user.email, module=ModuleType.ADMIN_USER,
                                     operation=OperationType.RESET_PASSWORD, detail=f'重置 {uid_user.email} 的密码')
        db.session.add(operation_log)
        db.session.commit()
        return jsonify({'message': '重置密码成功', 'errcode': '0'}), 200
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify({'message': '重置密码失败', 'errcode': '-1', 'error': str(e)}), 500


@login_bp.route('/change_password', methods=['POST'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
def change_password():
    id = request.json.get('id')
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')
    uid = request.json.get('uid')
    user = User.query.get(id)
<<<<<<< HEAD
    
    if not user.check_password(old_password):
        return jsonify({'message':'旧密码错误','errcode':'-1'}),400
    user.password = generate_password_hash(new_password)
    try:
        uid_user = User.query.get(uid)
        operation_log = OperationLog(user_id=uid,email=uid_user.email,module=ModuleType.USER_PROFILE,operation=OperationType.CHANGE_PASSWORD,detail=f'修改 {uid_user.email} 的密码')
        db.session.add(operation_log)
        db.session.commit()
        return jsonify({'message':'修改密码成功','errcode':'0'}),200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message':'修改密码失败','errcode':'-1','error':str(e)}),500
    
@login_bp.route('/menu/list',methods=['GET'])
=======

    if not user.check_password(old_password):
        return jsonify({'message': '旧密码错误', 'errcode': '-1'}), 400
    user.password = generate_password_hash(new_password)
    try:
        uid_user = User.query.get(uid)
        operation_log = OperationLog(user_id=uid, email=uid_user.email, module=ModuleType.USER_PROFILE,
                                     operation=OperationType.CHANGE_PASSWORD, detail=f'修改 {uid_user.email} 的密码')
        db.session.add(operation_log)
        db.session.commit()
        return jsonify({'message': '修改密码成功', 'errcode': '0'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '修改密码失败', 'errcode': '-1', 'error': str(e)}), 500


@login_bp.route('/menu/list', methods=['GET'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
def menu_list():
    id = request.args.get('id')
    user = User.query.get(id)
    if 'admin' in user.role.code.lower():
        title = '后台管理系统'
        menuList = [
            {
                "path": '/admin/index',
                "title": '首页',
                "icon": 'home'
            },
            {
                "path": '/admin/user',
                "title": '用户管理',
                "icon": 'user',
                "children": [
                    {
                        "path": '/admin/user',
                        "title": '账号列表',
                    },
                    {
                        "path": '/admin/user_info',
                        "title": '用户列表',
                    }
                ]
            },
            {
                "path": '/admin/role',
                "title": '权限管理',
                "icon": 'lock-on',
                "children": [
                    {
                        "path": '/admin/role',
                        "title": '角色列表',
                    },
                    {
                        "path": '/admin/permission',
                        "title": '权限列表',
                    },
                ]
            },
            {
                "path": '/admin/login_log',
                "title": '日志管理',
                "icon": 'system-log',
                "children": [
                    {
                        "path": '/admin/login_log',
                        "title": '登录日志',
                    },
                    {
                        "path": '/admin/operation_log',
                        'title': '操作日志',
                    }
                ]
            },
        ]
    else:
<<<<<<< HEAD
        title='百科全书'
        menuList=[
            {
            "path": '/user/index',
            "title": '首页',
            "icon": 'home'
=======
        title = 'AI管理平台'
        menuList = [
            {
                "path": '/user/index',
                "title": '首页',
                "icon": 'home'
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
            },
        ]

    data = {
<<<<<<< HEAD
        'title':title,
        'menuList':menuList
    }
    
    
    return jsonify({'message':'获取菜单成功','errcode':'0','data':data}),200
=======
        'title': title,
        'menuList': menuList
    }

    return jsonify({'message': '获取菜单成功', 'errcode': '0', 'data': data}), 200
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
